package com.zx.onlineeducation.service.ucenter.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * RestTemplate 配置类
 *
 * @author 郑雪
 * @since 2022-01-28
 */
@Configuration
public class RestTemplateConfig {

    /**
     * 发送http请求的工具类
     */
    @Bean
    public RestTemplate getRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // 指定字符编码为UTF-8,原编码为ISO-8859-1
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        // RestTemple默认能转换为application/json，转换追加text/plain类型
        restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
        return restTemplate;
    }

    /**
     * 微信返回的contentType为text/plain，需要追加转换类型
     */
    private static class WxMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
        private WxMappingJackson2HttpMessageConverter() {
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.TEXT_PLAIN);
            setSupportedMediaTypes(mediaTypes);
        }
    }
}
